/*Copyright (C) $today.year  深圳极向量科技有限公司 All Rights Reserved.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.*/

package neatlogic.module.change.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import neatlogic.framework.asynchronization.threadlocal.UserContext;
import neatlogic.framework.auth.core.AuthAction;
import neatlogic.framework.change.constvalue.ChangeAuditType;
import neatlogic.framework.change.dto.*;
import neatlogic.framework.change.exception.ChangeHandleHasNotStartedException;
import neatlogic.framework.change.exception.ChangeStepCommentNotFoundException;
import neatlogic.framework.change.exception.ChangeStepNotFoundException;
import neatlogic.framework.common.constvalue.ApiParamType;
import neatlogic.framework.crossover.CrossoverServiceFactory;
import neatlogic.framework.exception.file.FileNotFoundException;
import neatlogic.framework.exception.type.PermissionDeniedException;
import neatlogic.framework.file.dao.mapper.FileMapper;
import neatlogic.framework.process.auth.PROCESS_BASE;
import neatlogic.framework.process.crossover.IProcessStepHandlerCrossoverUtil;
import neatlogic.framework.process.dto.ProcessTaskStepVo;
import neatlogic.framework.restful.annotation.Description;
import neatlogic.framework.restful.annotation.Input;
import neatlogic.framework.restful.annotation.OperationType;
import neatlogic.framework.restful.annotation.Param;
import neatlogic.framework.restful.constvalue.OperationTypeEnum;
import neatlogic.framework.restful.core.privateapi.PrivateApiComponentBase;
import neatlogic.module.change.dao.mapper.ChangeMapper;
import neatlogic.module.change.service.ChangeService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@Transactional
@AuthAction(action = PROCESS_BASE.class)
@OperationType(type = OperationTypeEnum.OPERATE)
public class ChangeStepCommentEditApi extends PrivateApiComponentBase {

    @Resource
    private ChangeMapper changeMapper;

    @Resource
    private ChangeService changeService;

    @Resource
    private FileMapper fileMapper;

    @Override
    public String getToken() {
        return "change/step/comment/edit";
    }

    @Override
    public String getName() {
        return "nmca.changestepcommenteditapi.getname";
    }

    @Override
    public String getConfig() {
        return null;
    }

    @Input({
            @Param(name = "id", type = ApiParamType.LONG, isRequired = true, desc = "common.id"),
            @Param(name = "content", type = ApiParamType.STRING, desc = "common.content"),
            @Param(name = "fileIdList", type = ApiParamType.JSONARRAY, desc = "common.fileidlist"),
            @Param(name = "source", type = ApiParamType.STRING, desc = "common.source")
    })
    @Description(desc = "nmca.changestepcommenteditapi.getname")
    @Override
    public Object myDoService(JSONObject jsonObj) throws Exception {
        Long id = jsonObj.getLong("id");
        ChangeStepCommentVo commentVo = changeMapper.getChangeStepCommentById(id);
        if (commentVo == null) {
            throw new ChangeStepCommentNotFoundException(id);
        }
        ChangeStepVo changeStep = changeMapper.getChangeStepById(commentVo.getChangeStepId());
        if (changeStep == null) {
            throw new ChangeStepNotFoundException(commentVo.getChangeStepId());
        }
        if (changeService.isEditableComment(commentVo) == 0) {
            throw new PermissionDeniedException();
        }

        changeMapper.getChangeLockById(commentVo.getChangeId());
        ChangeStepCommentVo comment = new ChangeStepCommentVo();
        comment.setId(id);
        comment.setLcu(UserContext.get().getUserUuid());

        String content = jsonObj.getString("content");
        if (StringUtils.isNotBlank(content)) {
            ChangeContentVo contentVo = new ChangeContentVo(content);
            changeMapper.replaceChangeContent(contentVo);
            comment.setContentHash(contentVo.getHash());
        }

        if (StringUtils.isNotBlank(commentVo.getFileIdListHash())) {
            String fileIdListString = changeMapper.getChangeContentByHash(commentVo.getFileIdListHash());
            if (StringUtils.isNotBlank(fileIdListString)) {
                List<Long> fileIdList = JSON.parseArray(fileIdListString, Long.class);
                for (Long fileId : fileIdList) {
                    changeMapper.deleteChangeStepFileByFileId(fileId);
                }
            }
        }
        List<Long> fileIdList = JSON.parseArray(JSON.toJSONString(jsonObj.getJSONArray("fileIdList")), Long.class);
        if (CollectionUtils.isNotEmpty(fileIdList)) {
            for (Long fileId : fileIdList) {
                if (fileMapper.getFileById(fileId) == null) {
                    throw new FileNotFoundException(fileId);
                }
                changeMapper.insertChangeStepFile(new ChangeStepFileVo(commentVo.getChangeId(), commentVo.getChangeStepId(), fileId));
            }
            ChangeContentVo fileContent = new ChangeContentVo(JSON.toJSONString(fileIdList));
            changeMapper.replaceChangeContent(fileContent);
            comment.setFileIdListHash(fileContent.getHash());
        }
        changeMapper.updateChangeStepCommentById(comment);

        ProcessTaskStepChangeVo processTaskStepChangeVo = changeMapper.getProcessTaskStepChangeHandleByChangeId(commentVo.getChangeId());
        if (processTaskStepChangeVo == null) {
            throw new ChangeHandleHasNotStartedException();
        }

        ProcessTaskStepVo currentProcessTaskStepVo = new ProcessTaskStepVo();
        currentProcessTaskStepVo.setProcessTaskId(processTaskStepChangeVo.getProcessTaskId());
        currentProcessTaskStepVo.setId(processTaskStepChangeVo.getProcessTaskStepId());
        currentProcessTaskStepVo.getParamObj().put("changeStepName", changeStep.getName());
        currentProcessTaskStepVo.getParamObj().put("source", jsonObj.getString("source"));
        IProcessStepHandlerCrossoverUtil processStepHandlerCrossoverUtil = CrossoverServiceFactory.getApi(IProcessStepHandlerCrossoverUtil.class);
        processStepHandlerCrossoverUtil.audit(currentProcessTaskStepVo, ChangeAuditType.EDITCOMMENTCHANGESTEP);
        return null;
    }

}
